window.onload = () => {
  const mycanvas = document.querySelector('canvas')
  const myvideo = document.querySelector('video')
  const ctx = mycanvas.getContext('2d')
  const videoScrollContainer = document.querySelector('.video-scroll-container')

  if (!mycanvas || !myvideo || !ctx || !videoScrollContainer) {
    console.error('关键元素未找到')
    return
  }

  const getScreenDimensions = () => {
    mycanvas.width = window.innerWidth
    mycanvas.height = window.innerHeight
    if (myvideo.readyState > 1) {
      ctx.drawImage(myvideo, 0, 0, mycanvas.width, mycanvas.height)
    }
  }

  myvideo.addEventListener('loadedmetadata', () => {
    const scrollHeightForVideo = myvideo.duration * 100
    videoScrollContainer.style.height = `${scrollHeightForVideo + window.innerHeight}px`
    myvideo.currentTime = 0.01
  })

  const drawFrame = () => {
    ctx.drawImage(myvideo, 0, 0, mycanvas.width, mycanvas.height)
  }

  myvideo.addEventListener('seeked', drawFrame)

  let rafId
  window.addEventListener('scroll', () => {
    if (!myvideo.duration) return
    //后续呢就是可以可以考虑处理整个透明景深的效果。(透明叠加,增加这个视频帧的渲染效果)
    cancelAnimationFrame(rafId)
    rafId = requestAnimationFrame(() => {
      const scrollTop = window.scrollY || document.documentElement.scrollTop
      const videoTime = scrollTop / 100
      const clampedTime = Math.min(myvideo.duration - 0.01, Math.max(0, videoTime))

      if (Math.abs(clampedTime - myvideo.currentTime) > 0.05) {
        myvideo.currentTime = clampedTime
      }
    })
  })

  getScreenDimensions()
  myvideo.load()
  window.addEventListener('resize', getScreenDimensions)
}
